'use client';

import { queryRolePermissionsById } from '@/services/api';
import { useQuery } from '@tanstack/react-query';
import type {
  IPagination,
  IPermission,
  IQueryParams,
  IRole,
} from '@/interfaces';
import { useState } from 'react';
import Alert from '@/app/[locale]/alert/alert';
import AlertLoad from '@/app/[locale]/alert/load';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import Pagination from '@/app/[locale]/admin/common/pagination';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

export default function QueryRolePermissions({
  source,
  translatedFields,
}: {
  source: IRole;
  translatedFields: PrefixedTTranslatedFields<'roleAdminPage'>;
}) {
  const [params, setParams] = useState<IQueryParams>({
    page: 0,
  });

  const queryRolePermissionsByIdQuery = useQuery(
    ['/roles', source.id, '/permissions', params],
    async (context) => {
      return (await queryRolePermissionsById({
        id: context.queryKey[1] + '',
        query: context.queryKey[3] as any,
      })) as IPagination<IPermission>;
    },
    {
      keepPreviousData: true,
    },
  );

  function onClickPrevious() {
    const data = queryRolePermissionsByIdQuery.data;
    if (!data) {
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryRolePermissionsByIdQuery.data;
    if (!data) {
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  if (queryRolePermissionsByIdQuery.data) {
    const data = queryRolePermissionsByIdQuery.data;

    return (
      <div className="card">
        <div className="card-header bg-transparent text-secondary">
          <i className="bi bi-shield me-2"></i>
          {translatedFields.properties.permission}
        </div>
        <div className="card-body">
          <div className="table-responsive">
            <table className="table align-middle">
              <thead>
                <tr className="text-nowrap">
                  <th scope="col" className="fw-normal">
                    {translatedFields.properties.alias} / ID
                  </th>
                </tr>
              </thead>
              <tbody>
                {data.content.map((item) => {
                  return (
                    <tr key={item.id} className="text-nowrap">
                      <td>
                        {item.alias}&nbsp;(ID.&nbsp;{item.id})
                      </td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          {data.content.length === 0 && <Nodata />}

          <Pagination
            isShow={data.pageable.pages > 0}
            onPrevious={onClickPrevious}
            onNext={onClickNext}
            isPrevious={data.pageable.previous}
            isNext={data.pageable.next}
            translatedFields={translatedFields.pagination}
          />
        </div>
      </div>
    );
  }

  if (queryRolePermissionsByIdQuery.error) {
    return <Alert message={queryRolePermissionsByIdQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
